



gem
	parent_type=/obj/gettable/stackable
	icon='gems.dmi'
	stacksize = 9999

	New()
		..()
		icon_state=name

		if(findtext(name," "))
			icon_state = copytext(name, findtext(name, " ")+1)

	update()
		..()
		if(ismob(loc))
			loc << "You now have [amount] [src]."

obj/gem_mine
	icon = 'gems.dmi'
	density=1
	var
		spawn_type
		max_spawn = 10
		min_spawn = 2
		spawn_amt
		rarity  = 0

	New()
		..()
		spawn_amt = rand(min_spawn, max_spawn)
		icon_state="[name] Mine"

	LeftClick(mob/player/caller)
		if((caller in oview(1,src)) && spawn_amt-->0)
			if(prob(100-rarity))
				var/path = spawn_type
				if(prob(40))
					path = text2path("/gem/Rough_"+path)
				else if(prob(5))
					path = text2path("/gem/Polished_"+path)
				else
					path = text2path("/gem/"+path)
				new path(caller.loc, 1)

				caller << "A chunk of [clean_type_name("[path]")] falls to your feet!"
			else
				caller << "You fail to find anything."

		if(spawn_amt <= 0)
			var/turf/unbuildable/gem_generator/gg = loc
			gg.has_gem = 0
			del src

turf/unbuildable/gem_generator

	var
		has_gem = 0
		spawn_types
		spawn_range= 8
		spawn_time = 3600
		spawn_ability = 3

	New()
		..()
		spawn(rand(100,6000))
			while(src)
				var count=0
				for(var/turf/unbuildable/gem_generator/g in oview(src, spawn_range))
					if(g.has_gem) count++

				if(!has_gem && count < spawn_ability)
					respawn_gem()

				sleep(spawn_time)

	proc/respawn_gem()
		if(islist(spawn_types))
			for(var/o in spawn_types)
				if(prob(spawn_types[o]))
					new o(src)
					break

		else if(ispath(spawn_types))
			new spawn_types(src)

		else
			new /obj/gem_mine/Quartz(src)

		has_gem = 1

proc
	clean_type_name(string)
		. = copytext(string, findtext_last_of(string, "/")+1)
		. = replacetext(., "_", " ")


//credits to hiead.textlib
proc
	replacetext(haystack, needle, replace)
		var
			needleLen = length(needle)
			replaceLen = length(replace)
			pos = findtext(haystack, needle)
		while(pos)
			haystack = copytext(haystack, 1, pos) + \
				replace + copytext(haystack, pos+needleLen)
			pos = findtext(haystack, needle, pos+replaceLen)
		return haystack


	findtext_last_of(haystack, needle, pos=0)
		if(!pos) pos = length(haystack)
		var/needleLen = length(needle)
		. = 0
		for(var/i in 1 to needleLen)
			for(var/j=pos, j>., --j)
				if(cmptext(ascii2text(text2ascii(haystack, j)), \
					ascii2text(text2ascii(needle, i))))
					. = j
					break